﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight.Ioc;
using IkeCode.WP7.Toolkit.Persist;
using IkeCode.WP7.Toolkit;
using System.IO;
using GalaSoft.MvvmLight.Threading;

namespace IkeCode.WP7.HQReader.Base.Converters
{
    /// <summary>
    /// Get Image from Guid
    /// </summary>
    public class ImageUriToCachedImage : IValueConverter
    {
        /// <summary>
        /// Convert Guid to BitamapImage
        /// </summary>
        /// <param name="value">XAML source value</param>
        /// <param name="targetType">Target type</param>
        /// <param name="parameter">Parameter</param>
        /// <param name="culture">Culture</param>
        /// <returns>BitmapImage object</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is Uri)
            {
                try
                {
                    var url = (Uri)value;
                    var cacheService = SimpleIoc.Default.GetInstance<IcSmartPersistService>();
                    var image = new BitmapImage();

                    cacheService.TryGetImageCacheModel(url, (cacheModel, ex) =>
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            using (var ms = new MemoryStream(cacheModel.Bytes))
                            {
                                image.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                                image.SetSource(ms);
                            }
                        });
                    });

                    return image;
                    //return cacheModel.Bytes;
                }
                catch { }
            }

            return null;
        }

        /// <summary>
        /// Never used in this case but needed by IValueConverter
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter,
               CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}
